package socketdemo2;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*
 * 客户端
 * */
public class Client {

    private Socket socket;

    public Client() {
        try {
            //服务端所在的ip地址为127.0.0.1服务端在服务器上所使用的端口为8088
            socket = new Socket("127.0.0.1", 8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 作为程序的开始方法
     */
    private void start() {
        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            //如果想要服务端可以正确接收传输过去的信息 需要开启自动行刷新才可以
            PrintWriter pw = new PrintWriter(bw, true);

            Runnable r = new serverHandler();
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.start();

            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("请输入消息:");
                String line = scanner.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client c = new Client();
        c.start();
    }

    private class serverHandler implements Runnable {
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println("服务端返回的信息:" + line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
